package com.example.foobar.controller;

import com.alibaba.excel.EasyExcel;
import com.example.foobar.business.service.DaQrcodeRetentionRatesService;
import com.example.foobar.dto.RateDataForExcel;
import com.example.foobar.entity.DaQrcodeRetentionRates;
import com.example.foobar.entity.DaRetentionRates;
import com.example.foobar.vo.RetentionRateVO;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.controller.BaseController;
import io.geekidea.springbootplus.framework.core.pagination.Paging;
import io.geekidea.springbootplus.framework.core.validator.groups.Add;
import io.geekidea.springbootplus.framework.core.validator.groups.Update;
import io.geekidea.springbootplus.framework.log.annotation.Module;
import io.geekidea.springbootplus.framework.log.annotation.OperationLog;
import io.geekidea.springbootplus.framework.log.enums.OperationLogType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * 留存率记录 控制器
 *
 * @author 郑英奔
 * @since 2021-07-16
 */
@Slf4j
@RestController
@RequestMapping("/daQrcodeRetentionRates")
@Module("foobar")
@Api(value = "留存率记录API", tags = {"留存率记录"})
public class DaQrcodeRetentionRatesController extends BaseController {

    @Autowired
    private DaQrcodeRetentionRatesService daQrcodeRetentionRatesService;

    /**
     * 添加留存率记录
     */
    @PostMapping("/add")
    @RequiresPermissions("sys:qr-rate:page")
    @OperationLog(name = "添加留存率记录", type = OperationLogType.ADD)
    @ApiOperation(value = "添加留存率记录", response = ApiResult.class)
    public ApiResult<Boolean> addDaQrcodeRetentionRates(@Validated(Add.class) @RequestBody DaQrcodeRetentionRates daQrcodeRetentionRates) throws Exception {
        boolean flag = daQrcodeRetentionRatesService.saveDaQrcodeRetentionRates(daQrcodeRetentionRates);
        return ApiResult.result(flag);
    }

    /**
     * 修改留存率记录
     */
    @PostMapping("/update")
    @OperationLog(name = "修改留存率记录", type = OperationLogType.UPDATE)
    @ApiOperation(value = "修改留存率记录", response = ApiResult.class)
    @RequiresPermissions("sys:qr-rate:page")
    public ApiResult<Boolean> updateDaQrcodeRetentionRates(@Validated(Update.class) @RequestBody DaQrcodeRetentionRates daQrcodeRetentionRates) throws Exception {
        boolean flag = daQrcodeRetentionRatesService.updateDaQrcodeRetentionRates(daQrcodeRetentionRates);
        return ApiResult.result(flag);
    }

    /**
     * 删除留存率记录
     */
    @PostMapping("/delete/{id}")
    @OperationLog(name = "删除留存率记录", type = OperationLogType.DELETE)
    @ApiOperation(value = "删除留存率记录", response = ApiResult.class)
    @RequiresPermissions("sys:qr-rate:page")
    public ApiResult<Boolean> deleteDaQrcodeRetentionRates(@PathVariable("id") Long id) throws Exception {
        boolean flag = daQrcodeRetentionRatesService.deleteDaQrcodeRetentionRates(id);
        return ApiResult.result(flag);
    }

    /**
     * 获取留存率记录详情
     */
    @GetMapping("/info/{id}")
    @OperationLog(name = "留存率记录详情", type = OperationLogType.INFO)
    @ApiOperation(value = "留存率记录详情", response = DaQrcodeRetentionRates.class)
    @RequiresPermissions("sys:qr-rate:page")
    public ApiResult<DaQrcodeRetentionRates> getDaQrcodeRetentionRates(@PathVariable("id") Long id) throws Exception {
        DaQrcodeRetentionRates daQrcodeRetentionRates = daQrcodeRetentionRatesService.getById(id);
        return ApiResult.ok(daQrcodeRetentionRates);
    }

    /**
     * 留存率记录分页列表
     */
    @GetMapping("/getList")
    @RequiresPermissions("sys:qr-rate:page")
    @OperationLog(name = "查询二维码历史留存率", type = OperationLogType.PAGE)
    @ApiOperation(value = "查询二维码历史留存率", response = DaRetentionRates.class)
    public ApiResult<Paging<RetentionRateVO>> getList(String sceneId, Date startDate, Date endDate, int dayCount, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        ZonedDateTime zonedDateTime = LocalDate.now().atStartOfDay(ZoneId.systemDefault());
        Date today =Date.from(zonedDateTime.toInstant());
        Paging<RetentionRateVO> paging = daQrcodeRetentionRatesService.getQrCodeStroyRetentonRates(sceneId, startDate, today, dayCount);
        return ApiResult.ok(paging);
    }

    /**
     * 留存率记录分页列表
     */
    @GetMapping("/downLoad")
    @OperationLog(name = "下载二维码历史留存率", type = OperationLogType.PAGE)
    @ApiOperation(value = "下载二维码历史留存率", response = DaRetentionRates.class)
    @ResponseBody
    @RequiresPermissions("sys:qr-rate:page")
    public void downLoad(String sceneId, Date startDate, Date endDate, int dayCount, HttpServletResponse response) throws IOException {

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("活跃度", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        ZonedDateTime zonedDateTime = LocalDate.now().atStartOfDay(ZoneId.systemDefault());
        Date today =Date.from(zonedDateTime.toInstant());
        Paging<RetentionRateVO> paging = daQrcodeRetentionRatesService.getQrCodeStroyRetentonRates(sceneId, startDate, today, dayCount);

        EasyExcel.write(response.getOutputStream(), RateDataForExcel.class).sheet("模板").doWrite(RateDataForExcel.buildListRateDataForExcel(paging.getRecords()));
    }

}

